package uni.call.app;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ContactsActivity extends ListActivity
{
	private ListAdapter ContactsListAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);

	    //query for the people in your address book
	    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,ContactsContract.Contacts.DISPLAY_NAME + " ASC");
	    startManagingCursor(cursor);

	    //bind the name and the number fields
	    String[] columns = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
	    int[] to = new int[] { R.id.name_entry };
	    ContactsListAdapter = new ContactListCursorAdapter(this, R.layout.contacts, cursor, columns, to);
	    this.setListAdapter(ContactsListAdapter);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);
		Cursor ContactsCursor = (Cursor) ContactsListAdapter.getItem(position);
		startManagingCursor(ContactsCursor);
		    
		String ContactId = ContactsCursor.getString(
				ContactsCursor.getColumnIndex(ContactsContract.Contacts._ID) );
		String ContactName = ContactsCursor.getString(
				ContactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) );
		int ContactHasNum = ContactsCursor.getInt(
			ContactsCursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));


		if(ContactHasNum>0) 
		{
			Cursor PhonesCursor =getContentResolver().query(
					Phone.CONTENT_URI,
					null,
					Phone.CONTACT_ID + "=" + ContactId,
					null,
					null);
			
			if(PhonesCursor.getCount()==1) 
			{
				for(int k = 1; k<= PhonesCursor.getCount();k++)
				{
					PhonesCursor.moveToNext();
					String PhoneNum = PhonesCursor.getString(
							PhonesCursor.getColumnIndex(Phone.NUMBER));
					String Trimmed = RemoveSpecialChars(PhoneNum);
	            	DailerActivity.Peer = Trimmed;
	            	
	            	OutGoingCall.PeerProfileName = ContactName;
	            	
	            	ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
	         	    Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
	         	    
	         	    if(isWifi)
	         	    {
		            	if(HomeActivity.Registered.equals("true"))
		            	{
			            	Intent OutgoingIntent = new Intent(getApplicationContext(), OutGoingCall.class);
			            	OutgoingIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			            	OutgoingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			            	startActivity(OutgoingIntent);
		            	}
		            	else
		            	{
							AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
							builder2.setTitle(getString(R.string.NotRegisteredTitle));
							builder2.setMessage(getString(R.string.NotRegisteredMessage));
							builder2.setNeutralButton("Ok", null);
							builder2.show();
		            	}
	         	    }
	         	    else
	         	    {
						AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
						builder2.setTitle(getString(R.string.NoWiFiTitle));
						builder2.setMessage(getString(R.string.NoWiFiMessage));
						builder2.setNeutralButton("Ok", null);
						builder2.show();
	         	    }
				}
			}
			else if(PhonesCursor.getCount()>1) 
			{
			    final String[] PhoneNumbers = new String[PhonesCursor.getCount()];
				for(int k = 1; k<= PhonesCursor.getCount();k++)
				{
					PhonesCursor.moveToNext();
					String PhoneNum = PhonesCursor.getString(
							PhonesCursor.getColumnIndex(Phone.NUMBER));
					String Trimmed = RemoveSpecialChars(PhoneNum);
					
					PhoneNumbers[k-1] = Trimmed;
					OutGoingCall.PeerProfileName = ContactName;
				}
				

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(getString(R.string.Pick_Number));
				builder.setItems(PhoneNumbers, new DialogInterface.OnClickListener() 
				{
				    public void onClick(DialogInterface dialog, int item)
				    {	
				    	ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		         	    Boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
		         	    
		         	    if(isWifi)
		         	    {
					    	if(HomeActivity.Registered.equals("true"))
					    	{
					    		
						    	DailerActivity.Peer = PhoneNumbers[item];
						    	Intent OutgoingIntent = new Intent(getApplicationContext(), OutGoingCall.class);
				            	OutgoingIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				            	OutgoingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						    	startActivity(OutgoingIntent);
					    	}
					    	else
					    	{
								AlertDialog.Builder builder2 = new AlertDialog.Builder(ContactsActivity.this);
								builder2.setTitle(getString(R.string.NotRegisteredTitle));
								builder2.setMessage(getString(R.string.NoWiFiMessage));
								builder2.setNeutralButton("Ok", null);
								builder2.show();
					    	}
		         	    }
		         	    else
		         	    {
							AlertDialog.Builder builder2 = new AlertDialog.Builder(ContactsActivity.this);
							builder2.setTitle(getString(R.string.NoWiFiTitle));
							builder2.setMessage(getString(R.string.NoWiFiMessage));
							builder2.setNeutralButton("Ok", null);
							builder2.show();
		         	    }
				    }
				});
				builder.show();
			}
		}
		else 
		{
			Toast.makeText( this, getString(R.string.No_Number), Toast.LENGTH_SHORT).show();
		}
		
	}
	public String RemoveSpecialChars(String number)
    {
		String chars = "-";
        if(number.contains(chars))
        {
        	number = number.replace(chars,"");
        }

        return number;
    }
}
